#include "stdio.h"
#include "hitls_build.h"
#include "crypt_errno.h"
#include "crypt_encode_decode_key.h"
 #include "crypt_mldsa.h" 

 #include "hitls_error.h"
#include "bsl_obj.h"

#include "crypt_params_key.h"
#include "bsl_params.h"
#include "bsl_obj_internal.h"
#include "pqcp_decode_key_impl.h"

#include "pqcp_encode_decode_locacl.h"
#include "bsl_err_internal.h"

#ifdef HITLS_CRYPTO_KEY_DECODE


#define BSL_OID_GLOBAL 

typedef struct {
    BslOidString strOid;
    const char *oidName;
    BslCid cid;
} BslOidInfo;


int32_t ProcessMlDsaOids()
{
    int32_t ret = HITLS_SUCCESS;
    
    // 定义 BslOidInfo 数组，存储每个算法的 OID 数据、名称和 CID
    BslOidInfo mlDsaOids[] = {
        { {  9,"\2\20\1510\1\145\3\4\3\21", BSL_OID_GLOBAL }, "ML_DSA44", BSL_CID_ML_DSA44 },
        { { 9,"\2\20\1510\1\145\3\4\3\22",  BSL_OID_GLOBAL }, "ML_DSA65", BSL_CID_ML_DSA65 },
        { { 9,"\2\20\1510\1\145\3\4\3\23",  BSL_OID_GLOBAL }, "ML_DSA87", BSL_CID_ML_DSA87 }
    };

    // 使用循环遍历数组并调用 BSL_OBJ_Create
    for (int i = 0; i < sizeof(mlDsaOids) / sizeof(mlDsaOids[0]); i++) {
        ret = BSL_OBJ_Create(mlDsaOids[i].strOid.octs, mlDsaOids[i].strOid.octetLen, mlDsaOids[i].oidName, mlDsaOids[i].cid);
        if (ret != HITLS_SUCCESS) {
            return ret;
        }
    }
    return HITLS_SUCCESS;
}

// #ifndef HITLS_CRYPTO_MLDSA
#if defined(HITLS_CRYPTO_MLDSA) && defined(HITLS_CRYPTO_KEY_DECODE)
int32_t CRYPT_MLDSA_ParseSubPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, CRYPT_ML_DSA_Ctx **pubKey,
    bool isComplete)
{
    if (buff == NULL || buffLen == 0 || pubKey == NULL) {
        BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
        return CRYPT_NULL_INPUT;
    }
    CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0};
    int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete);//解析第一个sequence，得到算法类型
    if (ret != CRYPT_SUCCESS) {
        BSL_ERR_PUSH_ERROR(ret);
        return ret;
    }
    if (subPubkeyInfo.keyType != BSL_CID_ML_DSA44 && subPubkeyInfo.keyType != BSL_CID_ML_DSA65 && subPubkeyInfo.keyType != BSL_CID_ML_DSA87) {//BSL_CID_ML_DSA算法类型记得修改！
        BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
        return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
    }
    CRYPT_ML_DSA_Ctx *pctx = CRYPT_ML_DSA_NewCtx();
    if (pctx == NULL) {
        BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
        return CRYPT_MEM_ALLOC_FAIL;
    }
    BSL_Param pubParam[2] = {
        {CRYPT_PARAM_ML_DSA_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, 0},
        BSL_PARAM_END
    };
    ret = CRYPT_ML_DSA_SetPubKeyEx(pctx, pubParam);
    if (ret != CRYPT_SUCCESS) {
        BSL_ERR_PUSH_ERROR(ret);
        CRYPT_ML_DSA_FreeCtx(pctx);
        return ret;
    }
    *pubKey = pctx;
    return ret;

}
#else
// 添加错误处理
#error "ML-DSA support not enabled"


#endif

#endif
